package yzy.test.web.handler;

import yzy.test.beans.BeanFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

/**
 * 控制器的class元信息记录
 */
public class MappingHandler {

    /**
     * 控制器可以处理的 url
     */
    private String uri;

    /**
     * 控制器的信息,@Controller  @RequstMapping  @RequestParam注解的
     */
    private Class<?> controller;
    private Method method;
    private String[] args;

    public MappingHandler(String uri, Class<?> controller, Method method, String[] args) {
        this.uri = uri;
        this.controller = controller;
        this.method = method;
        this.args = args;
    }


    public boolean handle(ServletRequest req, ServletResponse res) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) req;
        String requestURI = httpServletRequest.getRequestURI();
        String queryString = httpServletRequest.getQueryString();//name=tom&age=35

        if(this.uri.equals(requestURI)){
            /**
             * 把queryString里面的参数与RequestParam里面的参数一一对应上
             */
            Object[] params = mappingParam(queryString);
            try {
                System.out.println("handle..." + this.toString());

             //   String resp = (String) method.invoke(controller.newInstance() , "tom","30");

                String resp = (String) method.invoke(/*controller.newInstance()*/ BeanFactory.getBean(controller), params);
                res.getWriter().println(resp);
            }  catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        }
        return false;

    }

    private String[] mappingParam(String queryString) {
          HashMap<String,String>  map = new HashMap<>();
          String[] params = queryString.split("&");
          for(String kv : params){
              String key = kv.split("=")[0];
              String value = kv.split("=").length > 1 ? kv.split("=")[1] : "";
              map.putIfAbsent(key,value);
          }

          ArrayList<String> values = new ArrayList(map.size());
          for(String p : this.args){
              String value = map.get(p);
              values.add(value);
          }
          return values.toArray(new String[values.size()]);
    }

    @Override
    public String toString() {
        return "MappingHandler{" +
                "uri='" + uri + '\'' +
                ", controller=" + controller +
                ", method=" + method +
                ", args=" + Arrays.toString(args) +
                '}';
    }
}
